package com.annotationAndReflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

//获得类的信息
public class GetClassInfo {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
        //通过反射获取
        Class c1 = Class.forName("com.annotationAndReflection.User");

//        User user = new User();
//        c1 = user.getClass();

        //获得类的名字
        System.out.println(c1.getName());//包名+类名
        System.out.println(c1.getSimpleName());//类名

        //获得类的属性
        System.out.println("=============");
        Field[] fields = c1.getFields();//只能找到public属性
        for (Field field : fields) {
            System.out.println(field);
        }
        Field[] declaredFields = c1.getDeclaredFields();//所有属性
        for (Field declaredField : declaredFields) {
            System.out.println(declaredField);
        }
        //获得指定属性的值
        Field name = c1.getDeclaredField("name");
        System.out.println(name);
        //获得类的方法
        System.out.println("======================");
        Method[] methods = c1.getMethods();//获得本类及其父类的全部public方法
        for (Method method : methods) {
            System.out.println("普通的："+method);
        }
        Method[] declaredMethods = c1.getDeclaredMethods();//获得本类的所有方法
        for (Method declaredMethod : declaredMethods) {
            System.out.println("declaredMethod"+declaredMethod);
        }

        //获得指定的方法
        //重载：需要传参，否则无法判断
        Method getName = c1.getMethod("getName", null);
        Method setName = c1.getMethod("setName", String.class);

        //获得构造器
        System.out.println("======================");
        Constructor[] constructors = c1.getConstructors();//public
        for (Constructor constructor : constructors) {
            System.out.println("普通的"+constructor);
        }
        Constructor[] declaredConstructors = c1.getDeclaredConstructors();//全部
        for (Constructor declaredConstructor : declaredConstructors) {
            System.out.println("declaredConstructor"+declaredConstructor);
        }
        //获得指定的构造器
        Constructor declaredConstructor = c1.getDeclaredConstructor(String.class, int.class, int.class);
        System.out.println("指定："+declaredConstructor);
    }
}

    